import 'dart:io';

import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/class_api.dart';
import 'package:FineArt/core/api/course_api.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/api/mqtt_service.dart';
import 'package:FineArt/core/api/resource_api.dart';
import 'package:FineArt/page/home/tab_home.dart';
import 'package:FineArt/page/imageview/StudentCourseView.dart';
import 'package:FineArt/page/imageview/TeacherCourseView.dart';
import 'package:FineArt/page/tab/TabNavigator.dart';
import 'package:FineArt/page/tab/my_courses_student.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/platform_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:FineArt/utils/sputils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bugly/flutter_bugly.dart';

// import 'package:flutter_svg_provider/flutter_svg_provider.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

import '../tab/discoverypage.dart';
import '../tab/my_courses_teacher.dart';
import '../tab/mypage.dart';

import 'dart:convert' as convert;

class TabMainPage extends StatefulWidget {
  TabMainPage(this.title, this.modules);

  final String title;
  final List<Module> modules;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<TabMainPage> {
  final List<Widget> pages = [];

  MqttServerClient mqttClient;
  void searchClick() {
    LogUtil.d("tabHomeClick>>>>>");
  }

  String _userTopic()
  {
    String uid = SPUtils.getUID();
    String topic =  "W0FIbOArG5CnyVViNU8CE3YbHt1u3Jyn/pcapi/person/" + uid+"/";
    return topic;
  }

  int _currentCourseid;

  String _courseTopic()
  {
    String topic =  "W0FIbOArG5CnyVViNU8CE3YbHt1u3Jyn/pcapi/" + _currentCourseid.toString() + "/";
    return topic;
  }

  @override
  void dispose() {
    FlutterBugly.dispose();
    super.dispose();
  }

  @override
  void initState() {
    if (Platform.isAndroid)
    FlutterBugly.init(androidAppId: "7068736e6d", customUpgrade: false);

    String role = SPUtils.getRole();
    if (role != "teacher") {
      MqttService.startMqtt(context);
    }

    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    //检查是否有正在进行的课程
    ClassApi().courseList().then((res) {
      if (res.code == 200) {
        if (res.data.length > 0) {
          showDialog(
              context: context,
              builder: (context1) {
                return AlertDialog(
                  title: Text('提示'),
                  content: Text('当前有正在进行的课程，是否进入'),
                  actions: <Widget>[
                    FlatButton(
                      child: Text('取消'),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                    FlatButton(
                      child: Text('进入课程'),
                      onPressed: () {
                        Navigator.of(context).pop();
                        //SystemNavigator.pop();
                        Course course = res.data[0];
                        //1:获取课程详情，以取得资源id
                        CourseApi().courseInfo(course.Id).then((res1) {
                          if (res1.code == 200) {
                            CourseInfo info = res1.data;
                            //2：根据资源ID获取资源详情
                            ResourceApi()
                                .resourceDetail(info.AssetId, course.AssetType)
                                .then((res2) {
                              if (res2.code == 200) {
                                ResourceDetail detail = res2.data;
                                if (detail.type == 1  || detail.type == 5001) //图片
                                {
                                  ResourceInfo1 info1 =
                                      detail.info as ResourceInfo1;
                                  String role = SPUtils.getRole();
                                  if (role == "teacher") {
                                    if (Platform.isAndroid)
                                    {
                                      PlatformUtil.startCourse(info1.hdurl, course.Id);
                                    }
                                    else
                                    {
                                      TeacherCourseView.Jump2CourseView(info1.hdurl, course.Id,context);
                                    }
                                  } else {
                                    StudentCourseView.Jump2CourseView(info1.hdurl, course.Id, context);
                                  }
                                }
                                if (detail.type == 0  || detail.type == 5000) //图书
                                    {
                                  ResourceInfo0 info0 =
                                  detail.info as ResourceInfo0;
                                  String role = SPUtils.getRole();
                                  String _hdurl = info0.hdurl + "/" + info.SubItem.toString() + info0.ext;
                                  if (role == "teacher") {
                                    if (Platform.isAndroid)
                                    {
                                      PlatformUtil.startCourse(_hdurl, course.Id);
                                    }
                                    else
                                    {
                                      TeacherCourseView.Jump2CourseView(_hdurl, course.Id,context);
                                    }
                                  } else {
                                    StudentCourseView.Jump2CourseView(_hdurl, course.Id, context);
                                  }
                                }
                              }
                            });
                          }
                        });
                      },
                    ),
                  ],
                );
              });
        }
      }
    });
  }

  final List<BottomNavigationBarItem> bottomNavItems = [
    BottomNavigationBarItem(
      backgroundColor: Colors.blue,
      icon: Image.asset(
        "assets/images/icon_tab_home.png",
        width: getPortraitSWidth(22.5),
        height: getPortraitSHeight(21),
      ),
      activeIcon: Image.asset(
        "assets/images/icon_tab_home_press.png",
        width: getPortraitSWidth(22.5),
        height: getPortraitSHeight(21),
      ),
      label: "素材",
    ),
    BottomNavigationBarItem(
      backgroundColor: Colors.green,
      icon: Image.asset(
        "assets/images/icon_tab_class.png",
        width: getPortraitSWidth(22.5),
        height: getPortraitSHeight(21),
      ),
      activeIcon: Image.asset(
        "assets/images/icon_tab_class_press.png",
        width: getPortraitSWidth(22.5),
        height: getPortraitSHeight(21),
      ),
      label: "课堂",
    ),
    // BottomNavigationBarItem(
    //   backgroundColor: Colors.amber,
    //   icon: Image.asset(
    //     "assets/images/icon_tab_discover.png",
    //     width: getPortraitSWidth(22.5),
    //     height: getPortraitSHeight(21),
    //   ),
    //   activeIcon: Image.asset(
    //     "assets/images/icon_tab_discover_press.png",
    //     width: getPortraitSWidth(22.5),
    //     height: getPortraitSHeight(21),
    //   ),
    //   label: "发现",
    // ),
    BottomNavigationBarItem(
      backgroundColor: Colors.red,
      icon: Image.asset(
        "assets/images/icon_tab_me.png",
        width: getPortraitSWidth(22.5),
        height: getPortraitSHeight(21),
      ),
      activeIcon: Image.asset(
        "assets/images/icon_tab_me_press.png",
        width: getPortraitSWidth(22.5),
        height: getPortraitSHeight(21),
      ),
      label: "我的",
    ),
  ];

  int currentIndex = 0;

  bool showBottomNavibar = true;

  void hideNavibar(bool hide) {
    setState(() {
      showBottomNavibar = !hide;
    });
  }

  @override
  Widget build(BuildContext context) {
    String role = SPUtils.getRole();
    Widget coursePage = null;
    if (role == "teacher") {
      coursePage = CoursesPageTeacher(setNavibarHidden: hideNavibar);
    } else {
      coursePage = CoursesPageStudent(setNavibarHidden: hideNavibar);
    }

    pages.addAll([
      TabHomePage(widget.modules),
      coursePage,
      // DiscoveryPage(),
      MyPage(),
    ]);

    return Scaffold(
      body: pages[currentIndex],
      bottomNavigationBar: Container(
        // height: showBottomNavibar ? -1 : 0,
        constraints: BoxConstraints(maxHeight: showBottomNavibar ? double.infinity : 0),
        child: BottomNavigationBar(
          items: bottomNavItems,
          currentIndex: currentIndex,
          type: BottomNavigationBarType.fixed,
          selectedItemColor: text_black,
          unselectedItemColor: text_black,
          selectedFontSize: setSp(11),
          unselectedFontSize: setSp(11),
          onTap: (index) => _changePage(index),
        ),
      ),
    );
  }

  /*切换页面*/
  void _changePage(int index) {
    /*如果点击的导航项不是当前项  切换 */
    if (index != currentIndex) {
      setState(() {
        currentIndex = index;
      });
    }
  }
}
